package com.ali.framework.app;

import android.Manifest;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.ali.framework.R;
import com.ali.framework.utils.CrashHandler;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;

import java.io.File;

public class App extends Application {
    private final String RECORD = "record";
    private final String CRASH = "crash";
    //全局上下文
    private static App sContext;

    @Override
    public void onCreate() {
        super.onCreate();
        // 加上下面两句话 防止7.0更新闪退
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        sContext = this;
        Utils.init(this);
        ToastUtils.setMsgTextSize(20);
        ToastUtils.setMsgColor(ContextCompat.getColor(this, R.color.Black_333333));
        ToastUtils.setBgColor(ContextCompat.getColor(this, R.color.White_F3F4F6));

        // 报错收集
        CrashHandler.getInstance().init(getApplicationContext());
        initLog();
    }

    public static App getAppContext() {
        return sContext;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
//        if (mIvw != null) {
//            mIvw.stopListening();
//        }
    }
    private void initLog() {
        String dataDir = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            dataDir = Environment.getExternalStorageDirectory().getPath() + File.separator
                    + getString(R.string.app_name);
        }

        LogUtils.getConfig().setLogSwitch(true)
                .setConsoleSwitch(true)
                .setGlobalTag("")
                .setLogHeadSwitch(true)
                .setLog2FileSwitch(true)
                .setDir(dataDir == null ? null : dataDir + File.separator + RECORD)
                .setBorderSwitch(true)
                .setConsoleFilter(LogUtils.V)
                .setFileFilter(LogUtils.V)
                .setSaveDays(3);

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            CrashUtils.init();
        } else {
            CrashUtils.init(dataDir + File.separator + CRASH);
        }
    }

}
